# -*- coding: utf-8 -*-
# @Time    : 2021/3/2 15:48
# @Author  : AkromA
# @File    : task_handle.py
# @Software: PyCharm
# @Info    : 生成房源自动采集任务

import time
from db.db_conn import DBHandle


# 生成任务
def task_create():

    # 连接数据库
    db_handle = DBHandle()

    # 从任务信息表中获取所有有效的地区信息，并生成对应的二手房、整租、合租的任务数据
    get_info_sql = "SELECT district_info_id, district_name, owner_short_name, district_code, SUBSTRING_INDEX(SUBSTRING_INDEX(a.data_source, ',' ,b.help_topic_id + 1), ',', '-1	') data_source FROM 08_district_info a JOIN mysql.help_topic b ON b.help_topic_id < (LENGTH(a.data_source) - LENGTH(REPLACE(a.data_source,',','')) + 1) WHERE state = 1;"
    result = db_handle.select_sql(get_info_sql)

    # print(result)
    if result:
        for r in result:
            # 每条数据要生成3条数据，分别为0=二手房，1=整租，2=合租
            for rent_type in ["0", "1", "2"]:
                district_info_id = r['district_info_id']
                task_info = r['district_name'] + "," + r['owner_short_name'] + "," + r['district_code'] + "," + r['data_source'] + rent_type
                task_create_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
                insert_task_sql = "INSERT INTO 08_task (`district_info_id`, `task_info`, `task_state`, `task_create_time`) VALUES ("
                insert_task_sql += "\"%s\", \"%s\", \"1\", \"%s\");" % (district_info_id, task_info, task_create_time)

                db_handle.insert_one(insert_task_sql)

    db_handle.close_db()


# 更新任务执行
def task_update_begin(task_id, ip):
    # 连接数据库
    db_handle = DBHandle()
    now_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
    update_sql = "UPDATE 08_task SET task_identity = \"%s\", task_begin_time = \"%s\", task_state = 2 WHERE task_id = \"%s\";" % (ip, now_time, task_id)
    db_handle.update_by_id(update_sql)
    db_handle.close_db()


# 更新任务完成
def task_update_ending(task_id):
    # 连接数据库
    db_handle = DBHandle()
    now_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
    update_sql = "UPDATE 08_task SET task_end_time = \"%s\", task_state = 3 WHERE task_id = \"%s\";" % (now_time, task_id)
    db_handle.update_by_id(update_sql)
    db_handle.close_db()


# 更新任务失败
def task_update_fail(task_id):
    # 连接数据库
    db_handle = DBHandle()
    now_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
    update_sql = "UPDATE 08_task SET task_end_time = \"%s\", task_state = 4 WHERE task_id = \"%s\";" % (now_time, task_id)
    db_handle.update_by_id(update_sql)
    db_handle.close_db()


if __name__ == '__main__':
    task_create()
